package com.regex.web.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 〈一句话功能简述〉<br> 
 * 订单工具类
 *
 * @author ocean.regex
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class OrderUtils {

    static Logger                 logger                = LoggerFactory.getLogger(OrderUtils.class);

    private final static String[] randomValuePool       = { "0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o",
            "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };

    private final static String[] randomNumberValuePool = { "0", "1", "2", "3", "4", "5", "6", "7",
            "8", "9" };
    private static long           orderNum              = 0l;
    private static String         date;

    /**
     * 订单号生成
     * 
     * @return
     */
    public static String createPayOrderNum() {
        String orderNum = randomString(32);
        return orderNum;
    }

    /**
     * 生成固定长度随机字符串
     * 
     * @param len
     *            长度
     * @return
     */
    private static String randomString(int len) {
        StringBuffer rs = new StringBuffer();
        int length = randomValuePool.length;
        // 两位随机数
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            int randomIndex = r.nextInt(length);
            rs.append(randomValuePool[randomIndex]);
        }

        return rs.toString();
    }

    /**
     * 创建数字类型固定长度随机字符串
     * 
     * @param len
     * @return
     */
    public static String randomNumberString(int len) {
        StringBuffer rs = new StringBuffer();
        int length = randomNumberValuePool.length;
        // 两位随机数
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            int randomIndex = r.nextInt(length);
            rs.append(randomNumberValuePool[randomIndex]);
        }
        return rs.toString();
    }

    /**
     * 获取字符串最后几位
     * 
     * @param value
     *            字符串
     * @param length
     *            长度
     * @return
     */
    public static String getLastLength(String value, int length) {
        int vLen = value.length();
        if (vLen >= length) {
            return value.substring(vLen - length);
        } else {
            return value;
        }
    }

    /**
     * 生成订单编号
     * 
     * @return
     */
    public static synchronized String getOrderNo() {
        String str = new SimpleDateFormat("yyMMddHHmm").format(new Date());
        if (date == null || !date.equals(str)) {
            date = str;
            orderNum = 0l;
        }
        orderNum++;
        long orderNo = Long.parseLong((date)) * 10000;
        orderNo += orderNum;
        ;
        return orderNo + "";
    }
}
